let _Vue = null

export default class VueRouter {
  static install(Vue) {
    // 判断当前插件是否安装
    if (VueRouter.install.installed) {
      return
    }

    // 标记是否安装过插件
    VueRouter.install.installed = true;

    // 把Vue构造函数保存到全局变量中
    _Vue = Vue;

    _Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          // 挂载到 Vue 原型上
          _Vue.prototype.$router = this.$options.router;
          this.$options.router.init();
        }
      }
    })
  }

  constructor(options) {
    this.options = options;
    this.routerMap = {};
    this.mode = options.mode;
    this.data = this.mode === 'hash' ? _Vue.observable({
      current: window.location.hash
    }) : _Vue.observable({
      current: window.location.pathname
    })
  }

  init() {
    this.createRouterMap();
    this.initComponent(_Vue);
    this.initEvent();
  }

  /**
   * 遍历所有的路由规则，把路由解析成键值对形式存储
   */
  createRouterMap() {
    this.options.routes.forEach(route => {
      this.routerMap[route.path] = route.component;
    })
  }

  /**
   * @param {*} Vue Vue实例，减少外部依赖
   */
  initComponent(Vue) {
    // 保存 this 
    const _this = this

    // 注册 router-link 组件
    Vue.component('router-link', {
      props: {
        to: String
      },
      render(h) {
        return h('a', {
          attrs: {
            href: this.to
          },
          on: {
            click: this.clickHandler
          }
        }, [this.$slots.default])
      },
      methods: {
        clickHandler(e) {
          const mode = this.$router.mode
          if (mode === 'hash') {
            window.location.hash = this.to;
          } else if (mode === 'history') {
            history.pushState({}, '', this.to) 
            this.$router.data.current = this.to
          }
          e.preventDefault();
        }
      }
    })

    // 注册 router-view 组件
    Vue.component('router-view', {
      render(h) {
        let component = null;
        if (_this.mode === 'hash') {
          // 获取 # 后面内容作为路由地址
          const current = _this.data.current.substr(1) || '/'
          component = _this.routerMap[current]
        } else if (_this.mode === 'history') {
          component = _this.routerMap[_this.data.current]
        }
        
        return h(component);
      }
    })
  }

  initEvent() {
    if (this.mode === 'hash') {
      // hashchange 事件监听路由地址的变化
      window.addEventListener('hashchange', () => {
        this.data.current = window.location.hash
      })
    } else if (this.mode === 'history') {
      window.addEventListener('popstate', () => {
        this.data.current = window.location.pathname;
      })
    }
  }
}